import {createRouter, createWebHistory} from "vue-router";
import MainLayout from "../components/MainLayout.vue";
import Dashboard from "../components/Dashboard.vue";

import InventoryCheck from "@/views/inventory/InventoryCheck.vue";
import DishesInventory from "@/views/inventory/DishesInventory.vue";
import MaterialsInventory from "@/views/inventory/MaterialsInventory.vue";

import DineInManagement from "@/views/business/DineInManage/DineInManagement.vue";
import DishCategory from "@/views/business/DishManage/DishCategory.vue";
import dish from "@/views/business/DishManage/dish.vue";
import Flavor from "@/views/business/DishManage/Flavor.vue";
import dish_spec from "@/views/business/DishManage/dish_spec.vue";
import material_category from "@/views/business/DishManage/material_category.vue";
import Ingredient from "@/views/business/DishManage/Ingredient.vue";
import { userStore } from '@/store/index.js'
import ingredient from "@/views/business/DishManage/Ingredient.vue";
import SitDownOrder from "@/views/indent/indent/Sit-downOrder.vue";
import Vip from "@/views/indent/vip/vip.vue";
import VipType from "@/views/indent/vip/vipType.vue";
import TakeoutOrder from "@/views/indent/indent/TakeoutOrder.vue";
import AdvanceOrder from "@/views/indent/indent/AdvanceOrder.vue";
import CouponList from "@/views/youhuiquan/CouponList.vue";
import AddCouponPage from "@/views/youhuiquan/AddCouponPage.vue";
import CouponDetailsPage from "@/views/youhuiquan/CouponDetailsPage.vue";
import DishSelector from "@/views/youhuiquan/DishSelector.vue";
import CategorySelector from "@/views/youhuiquan/CategorySelector.vue";

import Login from "@/components/Login.vue";
import {ElMessage} from "element-plus";

const routes = [
    {
        path: '/',
        redirect: '/login', // 根路径重定向到登录页
    },
    {
        path: '/MainLayout',
        component: MainLayout,
        redirect: '/dashboard',
        children: [
            {
                path: 'dashboard',
                name: 'Dashboard',
                component: Dashboard,
                meta: {title: '首页', icon: 'House'}
            },
            {
                path: '/device',
                name: 'Device',
                component: () => import('../views/store/device.vue'),
                meta: {title: '打印机管理', permission: 'device'}
            },
            {
                path: '/dine-in',
                name: 'dine-in',
                component: () => import('../views/store/DineInTicket.vue'),
                meta: {title: '堂食小票', permission: 'dine-in'}
            },
            {
                path: '/take-out',
                name: 'take-out',
                component: () => import('../views/store/TakeoutTicket.vue'),
                meta: {title: '外卖小票', permission: 'take-out'}
            },
            {
                path: '/recharge',
                name: 'recharge',
                component: () => import('../views/store/RechargeTicket.vue'),
                meta: {title: '充值小票', permission: 'recharge'}
            },
            {
                path: '/type',
                name: 'type',
                component: () => import('../views/store/TableTypeManager.vue'),
                meta: {title: '桌型管理', permission: 'type'}
            },
            {
                path: '/Alterable',
                name: 'Alterable',
                component: () => import('../views/store/TableManagement.vue'),
                meta: {title: '桌子一览', permission: 'Alterable'}
            },
            {
                path: '/create',
                name: 'create',
                component: () => import('../views/store/CreateTable.vue'),
                meta: {title: '新建台桌', permission: 'create'}
            }, {
                path: '/booking',
                name: 'booking',
                component: () => import('../views/store/ReservationSetting.vue'),
                meta: {title: '预订设置', permission: 'booking'}
            },
            {
                path: '/dishes',
                name: 'DishesInventory',
                component: DishesInventory,
                meta: {title: '菜品库存', icon: 'Box', permission: 'dishes'}
            },
            {
                path: '/materials',
                name: 'MaterialsInventory',
                component: MaterialsInventory,
                meta: {title: '原料库存', icon: 'Box', permission: 'materials'}
            },
            {
                path: '/check',
                name: 'InventoryCheck',
                component: InventoryCheck,
                meta: {title: '库存盘点', icon: 'Box', permission: 'check'}
            },
            {
                path: '/DineInManage',
                name: 'DineInManage',
                component: () => import('../views/business/DineInManage/DineInManagement.vue'),
                meta: {title: '堂食业务', icon: '', permission: 'DineInManage'}
            },
            {
                path: '/TakeOutManage',
                name: 'TakeOutManage',
                component: () => import('../views/business/TakeOutManage/TakeOutManagement.vue'),
                meta: {title: '外卖业务', icon: '', permission: 'TakeOutManage'}
            },
            {
                path: '/loginInfo',
                name: 'loginInfo',
                component: () => import('../views/store/loginInfo.vue'),
                meta: {permission: 'loginInfo'}
            },
            {
                path: '/dish_category',
                name: 'DishCategory',
                component: DishCategory,
                meta: {title: '菜品管理', icon: '', permission: 'dish_category'}
            },
            {
                path: '/dish',
                name: 'Dish',
                component: dish,
                meta: {title: '菜品管理', icon: '', permission: 'dish'}
            },
            {
                path: '/flavor',
                name: 'Flavor',
                component: Flavor,
                meta: {title: '菜品管理', icon: '', permission: 'flavor'}
            },
            {
                path: '/spec',
                name: 'Spec',
                component: dish_spec,
                meta: {title: '菜品管理', icon: '', permission: 'spec'}
            },
            {
                path: '/material_category',
                name: 'MaterialCategory',
                component: material_category,
                meta: {title: '菜品管理', icon: '', permission: 'material_category'}
            },
            {
                path: '/ingredient',
                name: 'Ingredient',
                component: Ingredient,
                meta: {title: '菜品管理', icon: '', permission: 'ingredient'}
            },
            {
                path: '/indent',
                name: 'Sit-downOrder',
                component: SitDownOrder,
                meta: {title: '查询堂食订单', icon: '', permission: 'indent'}
            },
            {
                path: '/TakeoutOrder',
                name: 'TakeoutOrder',
                component: TakeoutOrder,
                meta: {title: '查询外卖订单', icon: '', permission: 'TakeoutOrder'}
            },
            {
                path: '/AdvanceOrder',
                name: 'AdvanceOrder',
                component: AdvanceOrder,
                meta: {title: '查询预约订单', icon: '', permission: 'AdvanceOrder'}
            },
            {
                path: '/vip',
                name: 'Vip',
                component: Vip,
                meta: {title: '会员信息', icon: '', permission: 'vip'}
            },
            {
                path: '/vipType',
                name: 'VipType',
                component: VipType,
                meta: {title: '会员种类', icon: '', permission: 'vipType'}
            }
                meta: { title: '会员种类', icon: '' }
            },
            {
                path: 'CouponList',
                name: 'CouponList',
             component:CouponList,
                meta: {title: '优惠券', icon: '' }
            },
            {
                path: 'AddCouponPage/:id',
                name: 'AddCouponPage',
                component:AddCouponPage,
                meta: {title: '新增优惠券', icon: '' }
            },
            {
                path: 'AddCouponPage2',
                name: 'AddCouponPage2',
                component:AddCouponPage,
                meta: {title: '修改优惠券', icon: '' }
            },
            {
                path: 'CouponDetailsPage/:id',
                name: 'CouponDetailsPage',
                component: CouponDetailsPage,
            },
            {
                path: 'DishSelector',
                name: 'DishSelector',
                component: DishSelector,
            },
            {
                path: 'CategorySelector',
                name: 'CategorySelector',
                component: CategorySelector,
            },



        ]
    },
    {
        path: '/login',
        name: 'Login',
        component: () => import('../components/Login.vue'),
        meta: {permission: 'login'}
    },
    {
        path: "/",
        component: MainLayout,
        redirect: "/dashboard",
        children: [
            {
                path: "/dashboard",
                name: "Dashboard",
                component: Dashboard,
                meta: {title: "首页", icon: "House", permission: 'dashboard'}
            },
            {
                path: "/device",
                name: "Device",
                component: () => import("../views/store/device.vue"),
                meta: {title: "打印机管理", permission: 'device'}
            },
            {
                path: "/dine-in",
                name: "dine-in",
                component: () => import("../views/store/DineInTicket.vue"),
                meta: {title: "堂食小票", permission: 'dine-in'}
            },
            {
                path: "/take-out",
                name: "take-out",
                component: () => import("../views/store/TakeoutTicket.vue"),
                meta: {title: "外卖小票", permission: 'take-out'}
            },
            {
                path: "/recharge",
                name: "recharge",
                component: () => import("../views/store/RechargeTicket.vue"),
                meta: {title: "充值小票", permission: 'recharge'}
            },
            {
                path: "/dishes",
                name: "DishesInventory",
                component: DishesInventory,
                meta: {title: "菜品库存", icon: "Box", permission: 'dishes'}
            },
            {
                path: "/materials",
                name: "MaterialsInventory",
                component: MaterialsInventory,
                meta: {title: "原料库存", icon: "Box", permission: 'materials'}
            },
            {
                path: "/check",
                name: "InventoryCheck",
                component: InventoryCheck,
                meta: {title: "库存盘点", icon: "Box", permission: 'check'}
            },
            {
                path: "/DineInManage",
                name: "DineInManage",
                component: () =>
                    import("../views/business/DineInManage/DineInManagement.vue"),
                meta: {title: "堂食业务", icon: "", permission: 'DineInManage'}
            },
            {
                path: "/TakeOutManage",
                name: "TakeOutManage",
                component: () =>
                    import("../views/business/TakeOutManage/TakeOutManagement.vue"),
                meta: {title: "外卖业务", icon: "", permission: 'TakeOutManage'}
            },
            {
                path: "/DeliverySetting",
                name: "DeliverySetting",
                component: () =>
                    import("../views/business/TakeOutManage/DeliverySetting.vue"),
                meta: {title: "配送", icon: "", permission: 'DeliverySetting'}
            },
            {
                path: "/dishes",
                name: "DishesInventory",
                component: DishesInventory,
                meta: {title: "菜品库存", icon: "Box", permission: 'dishes'}
            },
            {
                path: "/materials",
                name: "MaterialsInventory",
                component: MaterialsInventory,
                meta: {title: "原料库存", icon: "Box", permission: 'materials'}
            },
            {
                path: "/check",
                name: "InventoryCheck",
                component: InventoryCheck,
                meta: {title: "库存盘点", icon: "Box", permission: 'check'}
            },
            {
                path: "/dine-in",
                name: "Dine-in",
                component: DineInManagement,
                meta: {title: "堂食订单", icon: "", permission: 'dine-in'}
            },
            {
                path: "/manage",
                name: "StoreManagement",
                component: () => import("../views/store/StoreManage.vue"),
                meta: {permission: 'StoreManagement'}
            },
            {
                path: "/schedule",
                name: "StaffSchedule",
                component: () => import("../views/store/StaffManage.vue"),
                meta: {permission: 'StaffSchedule'}
            },
            {
                path: "/list",
                name: "StaffList",
                component: () => import("../views/store/EmployeeList.vue"),
                meta: {permission: 'StaffList'}
            },
            {
                path: "/dish_category",
                name: "DishCategory",
                component: DishCategory,
                meta: {title: "菜品管理", icon: "", permission: 'dish_category'}
            },
            {
                path: "/dish",
                name: "Dish",
                component: dish,
                meta: {title: "菜品管理", icon: "", permission: 'dish'}
            },
            {
                path: "/flavor",
                name: "Flavor",
                component: Flavor,
                meta: {title: "菜品管理", icon: "", permission: 'flavor'}
            },
            {
                path: "/spec",
                name: "Spec",
                component: dish_spec,
                meta: {title: "菜品管理", icon: "", permission: 'spec'}
            },
            {
                path: "/material_category",
                name: "MaterialCategory",
                component: material_category,
                meta: {title: "菜品管理", icon: "", permission: 'material_category'}
            },
            {
                path: "/ingredient",
                name: "Ingredient",
                component: ingredient,
                meta: {title: "菜品管理", icon: "", permission: 'ingredient'}
            },
            {
                path: "/indent",
                name: "Sit-downOrder",
                component: SitDownOrder,
                meta: {title: "查询堂食订单", icon: "", permission: 'indent'}
            },
            {
                path: "/TakeoutOrder",
                name: "TakeoutOrder",
                component: TakeoutOrder,
                meta: {title: "查询外卖订单", icon: "", permission: 'TakeoutOrder'}
            },
            {
                path: "/AdvanceOrder",
                name: "AdvanceOrder",
                component: AdvanceOrder,
                meta: {title: "查询预约订单", icon: "", permission: 'AdvanceOrder'}
            },
            {
                path: "/vip",
                name: "Vip",
                component: Vip,
                meta: {title: "会员信息", icon: "", permission: 'vip'}
            },
            {
                path: "/vipType",
                name: "/VipType",
                component: VipType,
                meta: {title: "会员种类", icon: "", permission: 'vipType'}
            },
        ],
    },
    {
        path: "/login",
        name: "Login",
        component: () => import("../components/Login.vue"),
        meta: {permission: 'login'}
    },

];

const router = createRouter({
    history: createWebHistory(),
    routes,
});

// 在创建router实例后添加守卫
router.beforeEach(async (to, from, next) => {
    const store = userStore();
    const isLogin = store.loggedIn;

    // 登录页特殊处理
    if (to.path === '/login') {
        isLogin ? next('/dashboard') : next();
        return;
    }

    // 未登录跳转登录
    if (!isLogin) {
        next(`/login?redirect=${encodeURIComponent(to.fullPath)}`);
        return;
    }

    try {
        // 如果权限数据尚未加载，则等待加载完成
        if (!store.permissionsLoaded) {
            await store.fetchPermissions(store.user.id);
            store.permissionsLoaded = true; // 标记权限数据已加载
            console.log('权限数据加载完成:', store.permissions);
        }

        // 跳过 dashboard 路由的权限检查
        if (to.path === '/dashboard') {
            next();
            return;
        }

        // 权限校验逻辑
        const hasPermission = store.permissions.some(p => {
            const cleanPermissionPath = p.replace(/^\/|\/$/g, '');
            const cleanCurrentPath = to.path.replace(/^\/|\/$/g, '');

            const dynamicPattern = new RegExp(
                `^${cleanPermissionPath.replace(/:\w+/g, '([\\w-]+)')}$`
            );

            return dynamicPattern.test(cleanCurrentPath);
        });

        if (hasPermission) {
            next();
        } else {
            console.warn(`权限校验失败: 用户缺少 ${to.path} 的访问权限`);
            ElMessage.error('权限不足，请联系管理员');
            next(false);
        }
    } catch (error) {
        console.error('权限检查异常:', error);
        ElMessage.error('权限验证服务异常');
        next(false);
    }
});

export default router;


